package com.liu.stockmarket.ui.stock.add

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import androidx.core.os.bundleOf
import androidx.lifecycle.ViewModelProvider
import com.liu.stockmarket.BaseActivity
import com.liu.stockmarket.R
import com.liu.stockmarket.StockMarketApplication
import com.liu.stockmarket.databinding.ActivityStockAddBinding
import com.liu.stockmarket.model.Stock
import com.liu.stockmarket.repository.database.entity.TransactionRecordEntity
import com.liu.stockmarket.ui.search.SearchResultAdapter
import com.liu.stockmarket.utils.*
import com.lxj.xpopupext.popup.TimePickerPopup
import java.math.BigDecimal

class StockAddActivity : BaseActivity() {
    private lateinit var binding: ActivityStockAddBinding

    private lateinit var viewModel: StockAddViewModel

    /**
     * 是否使用再记
     * */
    private var isSaveAndAgain = false

    private var stock: SearchResultAdapter.Item? = null

    override fun initView(savedInstanceState: Bundle?) {
        binding = ActivityStockAddBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setToolbar(binding.toolbar.toolbar)

        val stockMarketApplication = this.application as StockMarketApplication

        viewModel =
            ViewModelProvider(
                this, StockAddViewModel.StockAddViewModelFactory(
                    stockMarketApplication.transactionRecordRepository,
                    stockMarketApplication.stockRepository,
                    stockMarketApplication.easyMoneyRepository
                )
            ).get(
                StockAddViewModel::class.java
            )

        intent.extras?.let {


            stock = it.getSerializable(STOCK_KEY) as SearchResultAdapter.Item


            if (stock == null) {
                this.toast("未设置股票")
                finish()
            }

            title = stock!!.stockType.text + "交易"
            viewModel.formChanged(
                true,
                stock = stock
            )

        }

    }

    override fun listener() {
        setToolbarButton("再记") {
            doSave(true)
        }
        binding.rlSelectDate.setOnClickListener {
            this.selectDate(TimePickerPopup.Mode.YMD) {
                viewModel.formChanged(true, transactionDate = it.toLocalDate())
            }
        }


        binding.etTransactionPrice.afterTextChanged {
            viewModel.formChanged(
                false, transactionPrice = if (it.isEmpty()) {
                    BigDecimal.ZERO
                } else if(it == "."){
                    BigDecimal.ZERO
                }else {
                    BigDecimal(it)
                }
            )
        }

        binding.etTransactionNumber.afterTextChanged {
            viewModel.formChanged(
                false, transactionNumber = if (it.isEmpty()) {
                    BigDecimal.ZERO
                }else if(it == "."){
                    BigDecimal.ZERO
                } else {
                    BigDecimal(it)
                }
            )
        }

        binding.etHandlingFee.afterTextChanged {
            viewModel.formChanged(
                false, stockHandlingFee = if (it.isEmpty()) {
                    BigDecimal.ZERO
                } else if(it == "."){
                    BigDecimal.ZERO
                }else {
                    BigDecimal(it)
                }
            )
        }

        binding.chipGroupSelectTransactionType.setOnCheckedChangeListener { _, checkedId ->
            viewModel.formChanged(
                true, transactionType = when (checkedId) {
                    R.id.chip_buy -> {
                        chipGroup(buy = false, sell = true)
                        TransactionRecordEntity.TransactionType.BUY

                    }
                    R.id.chip_sell -> {
                        chipGroup(buy = true, sell = false)
                        TransactionRecordEntity.TransactionType.SELL
                    }
                    else ->
                        throw IllegalArgumentException("只支持买入和卖出")
                }
            )
        }

        binding.btnSaveAndAgain.setOnClickListener {
            doSave(false)

        }

    }

    private fun chipGroup(buy: Boolean, sell: Boolean) {
        binding.chipBuy.isClickable = buy
        binding.chipSell.isClickable = sell
    }

    @SuppressLint("SetTextI18n")
    override fun observer() {
        viewModel.formState.observe(this) {
            binding.tvNameAndCode.text = "${it.stock?.name}（${it.stock?.code}）"

//            title = it.stock?.name
//            setSubTitle(it.stock?.code ?:"")

            if (it.transactionPrice == null) {
                binding.etTransactionPrice.setText("")
            }

            if (it.transactionNumber == null) {
                binding.etTransactionNumber.setText("")
            }

            if (it.stockHandlingFee != null && it.stockHandlingFee!! > BigDecimal.ZERO) {
                binding.etHandlingFee.setText(it.stockHandlingFee?.getString() ?: "")
            } else {
                binding.etHandlingFee.setText("")
            }

            with(binding.tvDate) {
                if (it.transactionDate == null) {
                    text = getString(R.string.click_to_select_date)
                    setTextColor(getColor(R.color.gray_double))
                } else {
                    text = it.transactionDate!!.YMD()
                    setTextColor(getColor(R.color.color_primary))
                }
            }

        }

        viewModel.validResult.observe(this) {
            if (it.transactionPrice != null) {
                binding.etTransactionPrice.error = it.transactionPrice
            }
            if (it.transactionNumber != null) {
                binding.etTransactionNumber.error = it.transactionNumber
            }

            if (it.transactionDate != null) {
                binding.tvDate.error = it.transactionDate
            } else {
                binding.tvDate.error = null
            }
            if (it.stockHandlingFee != null) {
                binding.etHandlingFee.error = it.stockHandlingFee
            }
        }

        viewModel.responseState.observe(this) {
            if (it.isSuccess()) {
                this.toast("保存成功")

                if (isSaveAndAgain) {
                    viewModel.clear()
                } else {
                    finish()
                }
            } else {
                this.toast(it.message)
            }
        }
    }


    private fun doSave(isSaveAndAgain: Boolean) {
        this.isSaveAndAgain = isSaveAndAgain
        viewModel.doSave()
    }


    companion object {
        private const val STOCK_ID_KEY = "stockId"
        private const val STOCK_CODE_KEY = "stockCode"
        private const val STOCK_NAME_KEY = "stockName"
        private const val TRANSACTION_EXCHANGE_KEY = "transactionExchange"
        private const val STOCK_KEY = "stock"

        @Deprecated(message = "过时")
        fun start(
            context: Context,
            stockCode: String,
            stockName: String,
            transactionExchange: Stock.TransactionExchange,
            stockId: Long? = null
        ) {
            context.start(
                bundleOf(
                    STOCK_ID_KEY to stockId,
                    STOCK_CODE_KEY to stockCode,
                    STOCK_NAME_KEY to stockName,
                    TRANSACTION_EXCHANGE_KEY to transactionExchange
                ), StockAddActivity::class.java
            )
        }

        fun start(context: Context, item: SearchResultAdapter.Item) {
            context.start(
                bundleOf(
                    STOCK_KEY to item,
                ), StockAddActivity::class.java
            )
        }
    }

}